package net.intidee.bean.session.persistenza;




import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;


import net.inteidee.bean.businessinterface.GenericDao;
import net.inteidee.bean.entity.Utente;

@Stateless
public abstract  class GenericDaoImpl<T> implements GenericDao{

	
	@PersistenceContext
	EntityManager em;
	
	 private Class<T> entityClass;

	
	 
	 public GenericDaoImpl(Class<T> entityClass) {
		 
	  this.entityClass = entityClass;
	  
	 }
	
	@Override
	public void save(Object entity) {
		// TODO Auto-generated method stub
		em.merge(entity);
	}



	@Override
	public void update(Object entity) {
		// TODO Auto-generated method stub
		em.merge(entity);
	}





	@Override
	//TODO Eliminazione Logica
	public <T> void delete(T entity) {
		// TODO Auto-generated method stub
		T entityToBeRemoved = em.merge(entity);//l'oggetto detached diventa managed
		
		//Effettuo cancellazione logica dell' utente
		if(entityToBeRemoved instanceof Utente){
			Utente u = (Utente) entityToBeRemoved;
			u.setStato(true);
			em.refresh(u);
			
		}
		else
			em.remove(entityToBeRemoved);

		
	}
	


	@Override
	public T find(long id) {
		// TODO Auto-generated method stub
		
		 
		 T object = em.find(entityClass, id);
		 
		 return object;
	}


	@Override
	public List<T> findAll() {
		// TODO Auto-generated method stub
		 List<T> list = null;
		 
		 	try {
				list = em.createQuery("from "+entityClass.getName()).getResultList();

			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
			
			return list;
	}


	@Override
	public List<T> findByProperty(String property, Object value) {
		// TODO Auto-generated method stub
		
		Query q = em.createQuery("from "+entityClass.getName() +" where "+property+"=:valueProperty");
		q.setParameter("valueProperty", value);
		
		return q.getResultList();
	}
	
}